<?php

namespace addons\sum\controller;

use addons\sum\controller\Common;
use app\admin\model\sum\Task as TaskModel;
use app\admin\model\sum\user\WalletLog;

class Task extends Common
{

    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $user = auth_user();
        // 使用 PHP 的反射 API 获取 模型 protected 属性
        // 获取多语言的字段
        $obj=new TaskModel();
        $reflection = new \ReflectionClass($obj);
        $property = $reflection->getProperty('lang_field');
        $property->setAccessible(true);
        $lang_field=$property->getValue($obj);
        // 获取当前语言标识
        $langSlug=$this->langSlug;

        $list_rows = $this->request->param('list_rows', 10);

        $map=[];
        $map['status']='normal';
        $type = $this->request->param('type', 'day');
        $is_recommend = $this->request->param('is_recommend');
        if($type){
            $map['type']=$type;
        }
        if($is_recommend==1){
            $map['is_recommend']=1;
        }
        $records=TaskModel::where($map)->paginate($list_rows);
        $records->each(function ($record)use($lang_field,$langSlug,$user){
            $record['is_receive']=0;
            if($user){
                $map_uwl=[];
                $map_uwl['user_id']=$user['id'];
                $map_uwl['type']='score';
                $map_uwl['event']=$record['hook'];//该任务事件产生的金币流水
                if($record['type']=='day'){
                    $today_date=strtotime('today');
                    $map_uwl['createtime']=['>=',$today_date];
                }
                $user_wallet_log=WalletLog::where($map_uwl)->find();
                if($user_wallet_log){
                    $record['is_receive']=1;
                }
            }
            foreach ($lang_field as $lfv){
                $record[$lfv]=$record['lang_data'][$langSlug][$lfv]?$record['lang_data'][$langSlug][$lfv]:$record[$lfv];
            }
            $record->hidden(['image','lang_data']);
        });
        $this->success(__('Success'),$records);
    }

}
